const path = require('path')
const fs = require('fs')
const mongoose = require('mongoose')
const config = require('./config')
const utils = require('./lib/utils')
const logger = require('./lib/logger')('app')

logger.debug('config: %j', config)

let app = require('koa')()

mongoose.Promise = global.Promise
mongoose.connect(utils.createConnStr(config.mongodb))
mongoose.connection.on('error', (err) => {
  logger.error(err)
  process.exit(1)
})

app.context.config = config
app.context.utils = utils
app.context.apiError = utils.apiError
app.context.apiSuccess = utils.apiSuccess
app.context.throwError = utils.throwError

// services
fs.readdirSync(path.join(__dirname, 'services'))
  .forEach((filename) => { app.context[`$${filename}`] = require(path.join(__dirname, 'services', filename)) })

app.use(require('koa-cors')())
app.use(require('koa-body')())
app.use(require('kcors')())
require('koa-validate')(app)

app.use(function * (next) {
  logger.info('%s', this.method, this.path)
  try {
    yield next
  } catch (err) {
    logger.warn('api error: %s', err.message)
    this.status = 200 // err.status || 500
    this.body = this.apiError(err.message)
  }
})

app.use(require('koa-jwt')({secret: config.app.secret}).unless({path: /^\/c/}))

// routes
let router = require('koa-router')()
fs.readdirSync(path.join(__dirname, 'api'))
  .forEach((filename) => { require(path.join(__dirname, 'api', filename))(router) })
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(config.app.port, () => logger.info('Server is listening on %s', config.app.port))
